#include "../logs/yhlog.h"
// 扩展一个以时间为条件文件滚动切换
// 实际上是以时间段
// time(nullptr)%gap
// time(nullptr)%60 当前就是第n个60s
enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};
class RollByTimeSink : public yhlog::LogSink
{
public:
    // 构造时传入文件名 并打开文件 将操作句柄管理起来
    RollByTimeSink(const std::string &basename, TimeGap gap_type) : _basename(basename)
    {
        switch (gap_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 1;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;
        case TimeGap::GAP_HOUR:
            _gap_size = 3600;
            break;
        case TimeGap::GAP_DAY:
            _gap_size = 3600 * 24;
            break;
        }
        _cur_gap = _gap_size == 1 ? yhlog::util::Date::now() : yhlog::util::Date::now() % _gap_size; // 当前是第几个时间段
        std::string filename = createNewFile();
        yhlog::util::File::createDirectory(yhlog::util::File::path(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    // 判断当前时间是否是当前文件的时间段，不是则切换文件
    void log(const char *data, size_t len)
    {
        time_t cur = yhlog::util::Date::now();
        if ((cur % _gap_size) != _cur_gap)
        { // 创建新文件
            _ofs.close();
            std::string filename = createNewFile();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    std::string createNewFile()
    {
        time_t t = yhlog::util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900;
        filename << lt.tm_mon + 1;
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";
        return filename.str();
    }

private:
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap;  // 当前是第几个时间段
    size_t _gap_size; // 时间段的大小
};
// void test_log()
// {
//     yhlog::Logger::ptr logger=yhlog::LoggerManager::getInstance().getlogger("async_logger");
//     logger->debug(__FILE__, __LINE__, "%s", "测试日志");
//     logger->info(__FILE__, __LINE__, "%s", "测试日志");
//     logger->warn(__FILE__, __LINE__, "%s", "测试日志");
//     logger->error(__FILE__, __LINE__, "%s", "测试日志");
//     logger->fatal(__FILE__, __LINE__, "%s", "测试日志");

//     size_t count = 0;
//     while (count < 500000)
//     {
//         logger->fatal(__FILE__, __LINE__, "测试日志-%d", count++);
//     }
// }
void test_log(const std::string &name)
{
    DEBUG("%s","测试开始");
    yhlog::Logger::ptr logger = yhlog::LoggerManager::getInstance().getlogger(name);
    // logger->debug("%s", "测试日志");
    // logger->info("%s", "测试日志");
    // logger->warn("%s", "测试日志");
    // logger->error("%s", "测试日志");
    // logger->fatal( "%s", "测试日志");

    // size_t count = 0;
    // while (count < 500000)
    // {
    //     logger->fatal("测试日志-%d", count++);
    // }
    DEBUG("%s", "测试日志");
    INFO("%s", "测试日志");
    WARN("%s", "测试日志");
    ERROR("%s", "测试日志");
    FATAL("%s", "测试日志");
    // size_t count = 0;
    // while (count < 500000)
    // {
    //     FATAL("测试日志-%d", count++);
    // }
    INFO("%s","测试完毕");
}
int main()
{
    // 工具类测试
    //  std::cout<<yhlog::util::Date::now()<<std::endl;

    // std::string pathname="./abc/bcd/a.txt";
    // yhlog::util::File::createDirectory(yhlog::util::File::path(pathname));

    // std::cout<<yhlog::LogLevel::toString(yhlog::LogLevel::value::DEBUG)<<std::endl;
    // std::cout<<yhlog::LogLevel::toString(yhlog::LogLevel::value::INFO)<<std::endl;
    // std::cout<<yhlog::LogLevel::toString(yhlog::LogLevel::value::WARN)<<std::endl;
    // std::cout<<yhlog::LogLevel::toString(yhlog::LogLevel::value::ERROR)<<std::endl;
    // std::cout<<yhlog::LogLevel::toString(yhlog::LogLevel::value::FATAL)<<std::endl;
    // std::cout<<yhlog::LogLevel::toString(yhlog::LogLevel::value::OFF)<<std::endl;
    // std::cout<<yhlog::LogLevel::toString(yhlog::LogLevel::value::UNKNOW)<<std::endl;

    // format.hpp
    // yhlog::LogMsg msg(yhlog::LogLevel::value::INFO, 53, "main.c", "root", "格式化功能测试....");

    // yhlog::Formatter fmt;

    // std::string str = fmt.format(msg);
    // std::cout << str << std::endl;

    // Sink
    // yhlog::LogSink::ptr stdout_lsp = yhlog::SinkFactory::create<yhlog::StdoutSink>();
    // yhlog::LogSink::ptr file_lsp = yhlog::SinkFactory::create<yhlog::FileSink>("./logfile/test.log");
    // yhlog::LogSink::ptr roll_lsp = yhlog::SinkFactory::create<yhlog::RollBySizeSink>("./logfile/rool-", 1024 * 1024);
    // yhlog::LogSink::ptr time_lsp = yhlog::SinkFactory::create<RollByTimeSink>("./logfile/rool-", TimeGap::GAP_SECOND);
    // time_t old = yhlog::util::Date::now();
    // while (yhlog::util::Date::now() - 5 < old)
    // {
    //     time_lsp->log(str.c_str(), str.size());
    //     sleep(1);
    // }
    // stdout_lsp->log(str.c_str(), str.size());
    // file_lsp->log(str.c_str(), str.size());
    // size_t cursize = 0;
    // size_t count = 0;
    // while (cursize < 1024 * 1024 * 10)
    // {
    //     std::string tmp = str + std::to_string(count++);
    //     roll_lsp->log(tmp.c_str(), tmp.size());
    //     cursize += tmp.size();
    // }

    // sync
    // std::string logger_name = "sync_logger";
    // yhlog::LogLevel::value limit = yhlog::LogLevel::value::WARN;
    // yhlog::Formatter::ptr fmt(new yhlog::Formatter("[%d{%H:%M:%S}][%c][%f:%l][%p]%T%m%n"));
    // yhlog::LogSink::ptr stdout_lsp = yhlog::SinkFactory::create<yhlog::StdoutSink>();
    // yhlog::LogSink::ptr file_lsp = yhlog::SinkFactory::create<yhlog::FileSink>("./logfile/test.log");
    // yhlog::LogSink::ptr roll_lsp = yhlog::SinkFactory::create<yhlog::RollBySizeSink>("./logfile/rool-", 1024 * 1024);

    // std::vector<yhlog::LogSink::ptr> sinks = {stdout_lsp, file_lsp, roll_lsp};
    // yhlog::Logger::ptr logger(new yhlog::SyncLogger(logger_name, limit, fmt, sinks));

    // std::unique_ptr<yhlog::LoggerBuilder> builder(new yhlog::GlobalLoggerBuilder());
    // builder->buildloggerName("async_logger");
    // builder->buildloggerLevel(yhlog::LogLevel::value::WARN);
    // builder->buildloggerFormatter("[%c][%f:%l]%m%n");
    // builder->buildloggerType(yhlog::LoggerType::LOGGER_ASYNC);
    // builder->buildEnableUnSafeAsync();
    // builder->buildSink<yhlog::FileSink>("./logfile/async.log");
    // builder->buildSink<yhlog::StdoutSink>();
    // builder->build();

    // test_log();

    // logger->debug(__FILE__, __LINE__, "%s", "测试日志");
    // logger->info(__FILE__, __LINE__, "%s", "测试日志");
    // logger->warn(__FILE__, __LINE__, "%s", "测试日志");
    // logger->error(__FILE__, __LINE__, "%s", "测试日志");
    // logger->fatal(__FILE__, __LINE__, "%s", "测试日志");

    // size_t cursize = 0;
    // size_t count = 0;

    // while (cursize < 1024 * 1024 * 10)
    // {
    //     logger->fatal(__FILE__, __LINE__, "测试日志-%d", count++);
    //     cursize += 20;
    // }

    // //读取文件数据，一点一点写入缓冲区，最终将缓冲区数据写入文件，判断生成的新文件与源文件是否一致
    // std::ifstream ifs("./logfile/test.log",std::ios::binary);
    // if(ifs.is_open()==false){std::cout<<"open failed!\n"; return -1;}
    // ifs.seekg(0,std::ios::end);//读写位置跳转到文件末尾
    // size_t fsize=ifs.tellg();//获取当前读写位置相对于起始位置的偏移量
    // ifs.seekg(0,std::ios::beg);//重新跳转到起始位置
    // std::string body;
    // body.resize(fsize);
    // ifs.read(&body[0],fsize);
    // if(ifs.good()==false){std::cout<<"read error\n";return -1;}
    // ifs.close();

    // std::cout<<fsize<<std::endl;
    // yhlog::Buffer buffer;
    // for(int i=0;i<body.size();i++)
    // {
    //     buffer.push(&body[i],1);
    // }
    // std::cout<<buffer.readAbleSize()<<std::endl;

    // std::ofstream ofs("./logfile/tmp.log",std::ios::binary);
    // //ofs.write(buffer.begin(),buffer.readAbleSize());
    // size_t rsize=buffer.readAbleSize();
    // for(int i=0;i<rsize;i++)
    // {
    //     ofs.write(buffer.begin(),1);
    //     if(ofs.good()==false){std::cout<<"write error!\n";return -1;}
    //     buffer.moveReader(1);
    // }
    // if(ofs.good()==false){std::cout<<"write error!\n";return -1;}
    // ofs.close();

    // ////async
    // std::unique_ptr<yhlog::LoggerBuilder>builder(new yhlog::LocalLoggerBuilder());
    // builder->buildloggerName("async_logger");
    // builder->buildloggerLevel(yhlog::LogLevel::value::WARN);
    // builder->buildloggerFormatter("[%c]%m%n");
    // builder->buildloggerType(yhlog::LoggerType::LOGGER_ASYNC);
    // builder->buildEnableUnSafeAsync();
    // builder->buildSink<yhlog::FileSink>("./logfile/async.log");
    // builder->buildSink<yhlog::StdoutSink>();
    // yhlog::Logger::ptr logger=builder->build();

    // logger->debug(__FILE__, __LINE__, "%s", "测试日志");
    // logger->info(__FILE__, __LINE__, "%s", "测试日志");
    // logger->warn(__FILE__, __LINE__, "%s", "测试日志");
    // logger->error(__FILE__, __LINE__, "%s", "测试日志");
    // logger->fatal(__FILE__, __LINE__, "%s", "测试日志");

    // size_t count = 0;
    // while (count<500000)
    // {
    //     logger->fatal(__FILE__, __LINE__, "测试日志-%d", count++);
    // }

    std::unique_ptr<yhlog::LoggerBuilder> builder(new yhlog::GlobalLoggerBuilder());
    builder->buildloggerName("async_logger");
    builder->buildloggerLevel(yhlog::LogLevel::value::WARN);
    builder->buildloggerFormatter("[%c][%f:%l][%p]%m%n");
    builder->buildloggerType(yhlog::LoggerType::LOGGER_ASYNC);
    builder->buildSink<yhlog::FileSink>("./logfile/async.log");
    builder->buildSink<yhlog::StdoutSink>();
    builder->buildSink<yhlog::RollBySizeSink>("./logfile/roll-async-by-size",1024*1024);
    builder->build();

    test_log("async_logger");
    return 0;
}